﻿var Context = {};

(function(){
    // public functions

    Context.loadContextData = function() {
        var _handlers, i, k;
        for ( k in schema) {
            if(localSettings[k]) {
                data[k] = localSettings[k];
                continue;
            }

            if (schema[k].defaultValue) {
                data[k] = schema[k].defaultValue;
            }
            else {
                data[k] = null;
            }

            _handlers = dataHandlers[k];
            if (_handlers) {
                for(i = 0; i < _handlers.length; i++) {
                    _handlers[i](data[k]);
                }
            }
        }
    };

    Context.saveContext = function(key) {
        localSettings[key] = data[key];
    }

    Context.applyToContext = function(key, value, applyer) {
        if (!applyer) applyer = data[key];
        if (!applyer) {
            data[key] = value;
        }
        else if (!value) {
            applyer = value;
        }
        localSettings[key] = data[key];
    }

    // private variables

    var localSettings = Windows.Storage.ApplicationData.current.localSettings.values;

    var data = {};

    var schema = {
        childId: {defaultValue:-1, type:'int'},
        weightUnit: {defaultValue:Constants.Unit.kgs},
        appInfo: {defaultValue:{appVer:Constants.appVer}, type:'object'},
        settings: {defaultValue:{},  type:'object'},
        logSettings: {defaultValue:[], type:'object'},
        app: {defaultValue:{},  type:'object'},
        needUpdate: {defaultValue:{app:{},user:{},addInvites:0}, type:'object'},
        lastModifiedByServer: {},
        products: {defaultValue:[], type:'object'},
        currentPageId: {},
        earnedPoints:{defaultValue:0, type:'int'},
        invitations: {defaultValue:[], type:'object'},
        lastPointAddedTime: {defaultValue:new Date(), type:'date'},
        installTime: {defaultValue: null, type:'date'},
        updateTime: {defaultValue:new Date(), type:'date'},
        lastLaunchedTime: {defaultValue:new Date(), type:'date'},
        lastFeedbackTime: {defaultValue: null, type: 'date'},
        lastFeedbackPromotionTime: {defaultValue: null, type: 'date'},
        gifted: {defaultValue: false}
    };

    var dataHandlers = {'weightUnit':[
        function(value) {
            console.log('is metric unit '+AAWE.Common.Util.isMetricUnit());
        }
    ]};

    // private functions
})();